from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler, FileSystemEvent
import os
import time
import re
import upload_video_to_douyin
import upload_video_to_tiktok


class MP4FileHandler(FileSystemEventHandler):
    def on_created(self, event: FileSystemEvent) -> None:
        if event.is_directory:
            return
        if event.src_path.endswith('.mp4'):
            print(f'New MP4 File creater:{event.src_path}')
            self.notify(event.src_path)
            try:
                # 执行抖音上传
                # upload_video_to_douyin.excute_upload()
                # 执行tk上传
                upload_video_to_tiktok.excute_tk_upload()
                # 发现文件变更以后生成对应的txt文件
                file_path = event.src_path
                # 获取文件名
                file_name = re.findall(pattern=r'(\D+|\d+.*).mp4', string=file_path)
            except Exception as e:
                print(e)



    def notify(self, file_path):
        # 这里实现通知逻辑，例如发送邮件、短信或者调用Webhook
        # 以下仅为示例，打印一条消息作为通知
        print(f"Notification: New file '{file_path}' has been created.")
        return file_path


# 开启监控
def start_monitoring(path):
    event_handler = MP4FileHandler()
    observer = Observer()
    # recursive=True表示递归监控子文件夹，现在不需要
    observer.schedule(event_handler, path, recursive=False)
    observer.start()
    # 无限循环执行监控，sleep保持监控的稳定运行
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    # 等待线程结束
    observer.join()


if __name__ == '__main__':
    parent_path = os.path.dirname(os.getcwd())
    target_path = 'videos/主页作品/走路摇zly/视频作品'
    folder_path = os.path.join(parent_path, target_path)
    start_monitoring(folder_path)
